package com.tanhua.admin.service;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.pojo.Admin;
import com.tanhua.model.vo.AdminVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

//    管理员登录
    public Map login(Map map) {
        String uuid = (String) map.get("uuid");
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        String verificationCode = (String) map.get("verificationCode");

        if (verificationCode==null){
            throw new BusinessException("验证码不能为空");
        }

        if (username==null||password==null){
            throw new BusinessException("账号密码不能为空");
        }
        String verificationCodeRed = redisTemplate.opsForValue().get(Constants.CAP_CODE+uuid);
        if (!verificationCodeRed.equals(verificationCode)){
            throw new BusinessException("验证码错误");
        }
        Admin admin = adminMapper.selectOne(Wrappers.lambdaQuery(Admin.class).eq(Admin::getUsername, username));

        if (admin == null||!admin.getPassword().equals(SecureUtil.md5(password))){
            throw new BusinessException("账号密码错误");
        }
//        使用工具类创造token
        Map params = new HashMap();
        params.put("id",admin.getId());
        params.put("username",username);

        String token = JwtUtils.getToken(params);

//        封装返回的结构数据
        Map retMap = new HashMap();
        retMap.put("token",token);
        return  retMap;
    }


//获得管理员信息
    public AdminVo profile() {
        Admin admin = adminMapper.selectOne(Wrappers.lambdaQuery(Admin.class).eq(Admin::getId, AdminHolder.getUserId()));

        return AdminVo.init(admin);
    }
}
